package com.lbs.jiepiaisi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.bean.HistoryTraceBean;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.StringUtil;
import com.lbs.jiepiaisi.utils.ToastUtil;
import com.lbs.jiepiaisi.view.CustomDatePicker;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class HistoryTraceActivity extends BaseActivity {

    private TextView textView0;
    private TextView textView1;

    private String startTime;
    private String endTime;

    private TabLayout tabLayout;

    private Button button;

    private CustomDatePicker startDatePicker,endDatePicker;
    private String eqNo,ownerName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_trace1);
        titleView.setText("轨迹查询");

        findView();
        initDataPicker();
        setListener();
        initData();

    }

    public void initData() {
        Intent intent = getIntent();
        eqNo = intent.getStringExtra("eqNo");
        ownerName = intent.getStringExtra("ownerName");
        Log.e("eqno&&ownername",eqNo + "--" + ownerName);
    }

    public void findView() {

        button = findViewById(R.id.btn_search);

        tabLayout = findViewById(R.id.layoutTab);
        tabLayout.addTab(tabLayout.newTab().setText("今天"));
        tabLayout.addTab(tabLayout.newTab().setText("昨天"));
        tabLayout.addTab(tabLayout.newTab().setText("自定义"));

        textView0 = findViewById(R.id.tv_start);
        textView1 = findViewById(R.id.tv_end);

        getTodayDate();
    }

    public void initDataPicker(){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String nowDate = sdf.format(new Date());

        //开始时间
        startDatePicker = new CustomDatePicker(this, time -> {// 回调接口，获得选中的时间

            if (!isDate2Bigger(time,textView1.getText().toString())) {
                ToastUtil.show("开始时间不能大于等于结束时间！");
                return;
            }

            startDatePicker.datePickerDialog.dismiss();
            textView0.setText(time);
        }, "2010-01-01 00:00", nowDate); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        startDatePicker.showSpecificTime(true); // 显示时和分
        startDatePicker.setIsLoop(true); // 允许循环滚动

        //结束时间
        endDatePicker = new CustomDatePicker(this, time -> {

            if (isDate2Bigger(time,textView0.getText().toString())) {
                ToastUtil.show("结束时间不能小于等于开始时间！");
                return;
            }

            endDatePicker.datePickerDialog.dismiss();

            textView1.setText(time);
        },"2010-01-01 00:00", nowDate);
        endDatePicker.showSpecificTime(true);
        endDatePicker.setIsLoop(true);
    }

    public int days(String smdate,String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {

        } catch (Exception e) {

        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }


    public void setListener() {

        button.setOnClickListener(v -> {
            String startTime = textView0.getText().toString() + ":00";
            String endTime = textView1.getText().toString() + ":00";

            int day = StringUtil.daysBetween(startTime,endTime);
            if (day > 1) {
                ToastUtil.show("只能查询一天的轨迹！");
                return;
            }

            Api.getInstance().createService()
                    .loadHistoryTrace(eqNo,startTime,endTime)
                    .compose(RxSchedulers.observableIO2Main(mContext))
                    .subscribe(new ProgressObserver<HistoryTraceBean>(mContext, true) {
                        @Override
                        public void onSuccess(HistoryTraceBean result) {
                            Intent intent = new Intent();
                            intent.putExtra("eqNo", eqNo);
                            intent.putExtra("ownerName", ownerName);
                            intent.putExtra("historyTraceBean", result);
                            intent.setClass(mContext, HistoryTracePlayActivity.class);
                            startActivity(intent);
                        }

                        @Override
                        public void onFailure(ErrorException e) {
                            if (e.getCode() == 1) {
                                ToastUtil.show("暂无轨迹数据");
                            }
                        }
                    });
        });

        textView0.setOnClickListener(v -> {
            Log.e("开始时间","开始时间");
            startDatePicker.show(textView0.getText().toString());
        });

        textView1.setOnClickListener(v -> {
            Log.e("结束时间","结束时间");
            endDatePicker.show(textView1.getText().toString());
        });


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                switch (tab.getPosition()) {
                    case 0:
                        reset(false);
                        getTodayDate();
                        break;
                    case 1:
                        reset(false);
                        getYesterdayDate();
                        break;
                    case 2:
                        reset(true);
                        getTodayDate();
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    public void getTodayDate() {
        Calendar now = Calendar.getInstance();
        String year = String.valueOf(now.get(Calendar.YEAR));
        String month = String.valueOf(now.get(Calendar.MONTH) + 1);
        if (month.length() == 1) {
            month = "0"+String.valueOf(now.get(Calendar.MONTH) + 1);
        }
        String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));

        textView0.setText(year+"-"+month+"-"+day+" "+"00:00");
        textView1.setText(year+"-"+month+"-"+day+" "+getNowDate());
    }

    public boolean isDate2Bigger(String str1, String str2) {
        boolean isBigger = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = sdf.parse(str1);
            dt2 = sdf.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt1.getTime() > dt2.getTime()) {
            isBigger = false;
        } else if (dt1.getTime() <= dt2.getTime()) {
            isBigger = true;
        }
        return isBigger;
    }

    public void getYesterdayDate() {
        Calendar now = Calendar.getInstance();
        String year = String.valueOf(now.get(Calendar.YEAR));
        String month = String.valueOf(now.get(Calendar.MONTH) + 1);
        String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH) - 1);

        textView0.setText(year+"-"+month+"-"+day+" "+"00:00");
        textView1.setText(year+"-"+month+"-"+day+" "+"23:59");
    }

    public String getNowDate(){
        return new SimpleDateFormat("HH:mm").format(new Date());
    }

    public void reset(boolean b){
        if (b) {
            textView0.setEnabled(true);
            textView1.setEnabled(true);
            textView0.setTextColor(getResources().getColor(R.color.base_color));
            textView1.setTextColor(getResources().getColor(R.color.base_color));
        } else {
            textView0.setEnabled(false);
            textView1.setEnabled(false);
            textView0.setTextColor(getResources().getColor(R.color.text_light_gray));
            textView1.setTextColor(getResources().getColor(R.color.text_light_gray));
        }
    }

}
